package com.gnerv.rabbitmq.agent.command;

import com.gnerv.rabbitmq.agent.model.entity.Node;
import com.gnerv.rabbitmq.agent.model.entity.Queue;
import com.gnerv.rabbitmq.agent.tools.ExecTools;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * @author Gnerv LiGen
 */
@Slf4j
public class QueueCommand extends AbstractRabbitmqctlCommand {

    /**
     * shellPath rabbitmqHome vhost queueName durable autoDelete arguments
     */
    private static final String CREATE_QUEUE_COMMAND = "sh %s %s %s %s %s %s %s";

    private QueueCommand(Node node) {
        super();
        setNode(node);
    }

    public static QueueCommand build(Node node) {
        return new QueueCommand(node);
    }

    // rabbitmqctl -n rabbit@bogon eval 'rabbit_amqqueue:declare({resource, <<"/">>, queue, <<"test-queue">>}, true, false, [{"x-max-length",100000},{"x-queue-type","classic"}], none, "").'
    // 'rabbit_amqqueue:declare({resource, <<"/">>, queue, <<"test-queue">>}, true, false, [{"x-max-length",100000},{"x-message-ttl",500000},{"x-queue-type","classic"}], none, "").'
    // 'rabbit_amqqueue:declare({resource, <<"/">>, queue, <<"%s">>}, %s, %s, [%s], none, "").'

    public ExecTools.ExecResult addQueue(Queue queue) {
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:command/queue_create.sh");
        } catch (FileNotFoundException e) {
            log.error("classpath:command/queue_create.sh 获取失败", e);
            throw new RuntimeException(e);
        }
        String absolutePath = file.getAbsolutePath();
        String command = String.format(CREATE_QUEUE_COMMAND, absolutePath, getNode().getPath(),
                queue.getVhost(), queue.getName(), queue.isDurable(),
                queue.isAutoDelete(), convertArguments(queue.getArguments()));
        return run(command, null);
    }


    public ExecTools.ExecResult deleteQueue(String name) {
        List<String> listQueues = Lists.newArrayList();
        listQueues.add("delete_queue");
        listQueues.add(name);
        return run(listQueues);
    }

    public ExecTools.ExecResult purgeQueue(String vhost, String name) {
        List<String> listQueues = Lists.newArrayList();
        listQueues.add("purge_queue");
        listQueues.add("-p");
        listQueues.add(vhost);
        listQueues.add(name);
        return run(listQueues);
    }


    public ExecTools.ExecResult listQueues() {
        List<String> listQueues = Lists.newArrayList();
        listQueues.add("list_queues");
        return run(listQueues);
    }

}
